import axios from 'axios'
import qs from 'qs'
import { ElMessage, ElLoading  } from 'element-plus'
import store from '@/store'
import cache from '@/utils/cache'
import { clearEmptyProp } from '@/utils/tool'
import { Storage } from '@/utils/storage'
import { BASE_URL_REQUEST } from '@/config/index'
let loading: any = null

// axios实例
const service = axios.create({
	baseURL: BASE_URL_REQUEST,
	timeout: 65000,
	headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// 请求拦截器
service.interceptors.request.use(
	(config: any) => {
		const userStore = store.userStore
		if (userStore?.token) {
			if (localStorage.getItem('user_system') == '2') {
				config.headers.Authorization = 'Bearer ' + userStore.token
			} else {
				config.headers.Authorization = 'Bearer ' + userStore.token
			}
		}

		config.headers['Accept-Language'] = cache.getLanguage()

		// 追加时间戳，防止GET请求缓存
		if (config.method?.toUpperCase() === 'GET') {
			config.params = { ...config.params, t: new Date().getTime() }
		}
		if(config.data?.canSendEmpty){
			// 带有这个属性的不清空空字段
			delete config.data.canSendEmpty
		}else{
			config.data = clearEmptyProp(config.data)
		}
		if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
			config.data = qs.stringify(config.data)
		}
		// console.log(config);
		if (config.loading && !loading) {
			
			const lang = localStorage.getItem('lang')
			let loadTips = ''
			if (!lang || lang.includes('zh-CN')) {
				loadTips = '加载中'
			} else {
				loadTips = 'Loading'
			}
			loading = ElLoading.service({
				lock: true,
				text: config.msg || loadTips,
				background: 'rgba(0, 0, 0, 0.1)',
			})
		}
		return config
	},
	error => {
		setTimeout(() => {
			if (loading) {
				loading.close()
				loading = null
			}
		}, 0);
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(
	response => {
		setTimeout(() => {
			if (loading) {
				loading.close()
				loading = null
			}
		}, 0);
		// // .console.log(response);
		if (response.status !== 200) {
			if (response.status === 401) {
				// const lang = localStorage.getItem('lang')
				// let error401 = ''
				// if (!lang || lang.includes('zh-CN')) {
				// 	error401 = '当前未登录或者登录已过期，请重新登录'
				// } else {
				// 	error401 = 'You are currently not logged in or your login has expired. Please log in again.'
				// }
				// Storage.setItem('login_tips', error401)
				// store.userStore.setToken('')
				// location.reload()
			}else{
				if (response.data.message && typeof response.data.message != 'string') {
					if (response.status == 202) {
						// 购买账号超出限制给出提示（202状态码专用）
						return Promise.reject('add-amount-max')
					} else if (response.status == 203) {
						// 添加产品或者导出文件上限给出提示（203状态码专用）
						return Promise.reject('product-export-max')
					} else {
						const lang = localStorage.getItem('lang')
						if (!lang || lang.includes('zh-CN')) {
							ElMessage.error(response.data.message.cn)
						} else {
							ElMessage.error(response.data.message.en)
						}
						console.log(lang, response.data.message);
					}
				} else {
					let error401 = response.data.error
					const lang = localStorage.getItem('lang')
					if(error401 == "账号或密码错误"){
						if (!lang || lang.includes('zh-CN')) {
							error401 = '账号或密码错误'
						} else {
							error401 = 'Account or password error'
						}
					}
					ElMessage.error(error401 || response.statusText || 'Error')
					return Promise.reject(new Error(response.data.message || response.statusText || 'Error'))
				}
			}
		}else{
			return response.data
		}
		return Promise.reject(new Error(response.statusText || 'Error'))
	},
	error => {
		setTimeout(() => {
			if (loading) {
				loading.close()
				loading = null
			}
		}, 0);
		let { response, config } = error
		// console.log(response);
		// 没有权限，如：未登录、登录过期等，需要跳转到登录页
		
        if (error.response.status == 422) {
            const errors: any = error.response.data.errors;
            ElMessage.error(Object.values(errors).join('、'));
            return Promise.reject(error)
        }
		if (response.status === 401) {
			// store.userStore.setToken('')
			// const lang = localStorage.getItem('lang')
			// let error401 = ''
			// if (!lang || lang.includes('zh-CN')) {
			// 	error401 = '当前未登录或者登录已过期，请重新登录'
			// } else {
			// 	error401 = 'You are currently not logged in or your login has expired. Please log in again.'
			// }
			// Storage.setItem('login_tips', error401)
			// location.reload()
		}else{
			if (response.data.message && typeof response.data.message != 'string') {
				const lang = localStorage.getItem('lang')
				if (!lang || lang.includes('zh-CN')) {
					ElMessage.error(response.data.message.cn)
				} else {
					ElMessage.error(response.data.message.en)
				}
				console.log(lang, response.data.message);
			} else if(config.url != '/api/main/student/get_openid'){
				ElMessage.error(error.message || error.data || 'error：'+error.code)
			}
			return Promise.reject(error)
		}
	}
)

// 导出 axios 实例
export default service
